
//引入moment模块
const moment = require('moment');
//引入数据库连接模块
const conn = require('../db/db.js');
//引入marked模块用来把文本内容转成HTML结构
const marked = require('marked');
//-------------------------------------写监听处理函数--------------------------------
//展示添加页面
const showAdd = (req,res) => {
    // console.log(req.session.user);   
    res.render('./article/add.ejs',{
        user:req.session.user,
        islogin:req.session.islogin
    })
}
//添加文章
const addArticle = (req,res) =>{
    // console.log(req.body);
    let content = req.body;
    content.ctime = moment().format('YYYY-MM-DD HH:mm:ss');
    //写sql语句添加到数据库
    let sql = "insert into blog_articles set ?";
    conn.query(sql,content,(err,result) => {
        if(err) return res.send({status:500,message:'添加文章失败'});
        if(result.affectedRows !=1) return res.end({status:501,message:'文章添加错误'});
        res.send({status:200,message:'文章添加成功',insertId:result.insertId});
    })
}
//展示文章详细信息页面
const showInfo = (req,res) => {
    let id = req.params.id;
    // console.log(id);
    //查询这个id对应的数据
    let sql = "select * from blog_articles where id=?";
    conn.query(sql,id,(err,result) => {
        if(err) return res.send('出错了!');
        if(result.length == 0) return res.send('查询失败');
        let html = marked(result[0].content);
        console.log(html);
        result[0].content = html;
        res.render('./article/info.ejs',{
            user:req.session.user,
            islogin:req.session.islogin,
            article:result[0]
        })
    })
}
//展示编辑页面
const showEdit = (req,res) =>{
    let id = req.params.id;
    // console.log(id);
    let sql = "select * from blog_articles where id=?";
    conn.query(sql,id,(err,result) => {
        if(err) return res.send('出错了');
        if(result.length == 0) return res.send('查询失败');
        // let html = marked(result[0].content);
        // result[0].content = html;
        res.render('./article/edit.ejs',{
            user:req.session.user,
            islogin:req.session.islogin,
            article:result[0]
        })
    })
    
}
const editArticle = (req,res) =>{
    // console.log(req.body);
    let article = req.body;
    // content.ctime = moment().format('YYYY-MM-DD HH:mm:ss');
    //写sql语句添加到数据库
    let sql = "update blog_articles set ? where id=?";
    conn.query(sql,[article,article.id],(err,result) => {
        if(err) return res.send({status:500,message:'编辑文章失败'});
        if(result.affectedRows !=1) return res.end({status:501,message:'文章编辑错误'});
        res.send({status:200,message:'文章编辑成功',id:article.id});
    })
}
//导出showAdd
module.exports = {
    showAdd,
    addArticle,
    showInfo,
    showEdit,
    editArticle
}